package Scuttlebutt;

import javax.swing.tree.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.*;
import java.io.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import glue.ftp.*;
import javax.swing.JOptionPane;


public class SortableNode extends DefaultMutableTreeNode implements Comparable// implements Transferable
{
	public String path = null;
	public String remote_dir = null;
	boolean bUploaded = true;
	boolean bURL = false;
	boolean bUploading = false;
	private float progress = 0;
	
	private boolean completedDownload = true;
	ArrayList<String> filesList = null;
	String link = null;
	
	

	public SortableNode(Object obj, String dir)
	{
    	super(obj);
    	setAllowsChildren(true);
//    	File f = new File(dir);
    	this.path = dir;//f.getPath();
    	filesList = new ArrayList<String>();
	}
	
	public SortableNode(Object obj)
	{
    	super(obj);
    	setAllowsChildren(true);
    	this.path = new String("");
    	filesList = new ArrayList<String>();
	}
	
	
	public String getRemote(){
		String remote = new String(new String((getRemoteDirectory().length() > 0)? new String(getRemoteDirectory() + File.separatorChar): "") + toString());
		return remote;
	}
	
	public void addFile(String path){
//		File f = new File(path);
		if(!filesList.contains(path))
			filesList.add(path);
	}
	
	public void removeFile(String path){
		File f = new File(path);
		filesList.remove(path);
	}


	public java.awt.Label getHTMLLink(){
		java.awt.Label h = new java.awt.Label(new String("<a href=\"" + remote_dir + File.separatorChar + new File(path).getName() + "\">" +  toString() + "</a>"));
		return h;
	}
	
	
	
	public int find(String txt){
		int idx =0;
		for (Enumeration e = children() ; e.hasMoreElements() ;) {
			DefaultMutableTreeNode child = (DefaultMutableTreeNode)e.nextElement();
			if(child.toString().compareToIgnoreCase(txt.toString()) == 0){
				return idx;
			}
			idx++;
		}
		return -1;
	}
	
	public Object Search(String txt){
		int idx = find(txt);
		return (idx != -1)? getChildAt(idx): null;
	}
	
	public void addSortable(SortableNode node){
		int count = getChildCount();
		if(count == 0){
			add(node);
		}else{
			insert(node, count);
		}
	}

	
	public void addSortable(URLNode node){
		int count = getChildCount();
		if(count == 0){
			add(node);
		}else{
			insert(node, count);
		}
	}
	
	
	public void addSortable(FolderNode node){
		int count = getChildCount();
		if(count == 0){
			add(node);
		}else{
			insert(node, 0);
		}
	}
	
	public void setUploadingState(boolean bUploading){
		bUploading = bUploading;
	}
	
	public boolean getUploadingState(){
		return bUploading;
	}
	
	public void setNodePath(String path){
		this.path = path;
	}

	public String getNodePath(){
		return path;
	}
	
	public void setRemoteDirectory(String dir){
		remote_dir = new String(dir);
//		link = new String("<a href=\"" + remote_dir + File.separatorChar + new File(path).getName() + "\">" +  toString() + "</a>");
//		LinksList.add(link);	
	}
	
	public String getRemoteDirectory(){
		return remote_dir;
	}
		
	public int compareTo(Object o){
		String text = toString();
		return text.compareTo(((DefaultMutableTreeNode)o).toString());
		
	}
	
	public boolean isUploaded(){
		return bUploaded;
	}
	
	public void setUploaded(boolean uploaded){
		bUploaded = uploaded;
	}
	
	public void setURL(boolean state){
		bURL = state;
	}
	
	public boolean isURL(){
		return bURL;
	}
	
	public float getProgress(){
		return progress;
	}
	
	public void setProgress(float progress){
		this.progress = progress;
	}
	
	
	public void moveWithoutCopy(Scuttlebutt parent, FolderNode dest){
	}
	
	public void move(Scuttlebutt parent, SortableNode node){//node is destination	
		File file = new File(path);
		File nFile = new File(node.getNodePath() + File.separatorChar + file.getName());

 	  	String remote = null;
 	  	
 	  	remote = (node.getRemoteDirectory().compareToIgnoreCase(/*"/"*/String.valueOf(File.separatorChar)) == 0)? "" :new String(new String((node.getRemoteDirectory().length() > 0)?node.getRemoteDirectory() + File.separatorChar: "") + node.toString());
 	  	
 	  	String a = new String(new String((node.getRemoteDirectory().length() > 0)?node.getRemoteDirectory() + File.separatorChar: "") + node.toString());
 	  	if(a.compareToIgnoreCase(getRemoteDirectory()) == 0){
 	  		return;
 	  	}
			
        //nFile is the destination path
        File dFile = new File(node.getNodePath() + File.separatorChar + toString());
        //if nFile exists ask, to delete it
		if(dFile.exists()){
		   	if(JOptionPane.showConfirmDialog(parent, new String("You are about to copy over \'" + dFile.getPath() +"\'. Do you want to continue?"), "Warning",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
				//remove the tab representing the destination file
				//if one exists.
				parent.getEditPane().remove(dFile.getPath());
				
				//Search the target node for a child bound to the
				//destination path and remove it
				Object r = node.Search(toString());
				if(r != null){
					parent.getProject().removeOpened(((SortableNode)r).getNodePath());
					((SortableNode)r).removeFromParent();
				}
				//remove the destination file
				dFile.delete();
				dFile = null;
				
				try{
					parent.getFTP().setDirectory(parent.getRemoteHomeDirectory());
					parent.getFTP().fileDelete(remote + File.separatorChar + file.getName());
				}catch(java.io.IOException e){
					System.err.println(e);
				}catch(FtpException f){
					System.err.println("Failed to move file:" + f);
				}
				
				
		   	}else{
			   	System.err.println("no option");
			   	return;
		   	}
		}	
	
 		removeFromParent();
 		
 	   	parent.getProject().removeOpened(getNodePath());
		//get the remote directory
		
		try{
			parent.getFTP().setDirectory(parent.getRemoteHomeDirectory());
			parent.getFTP().fileRename(getRemoteDirectory() + File.separatorChar + file.getName(), remote + File.separatorChar + file.getName());
		}catch(java.io.IOException e){
			System.err.println(e);
		}catch(FtpException f){
			System.err.println("Failed to move file:" + f);
		}
		
		try{
			if(!file.isFile()){
				System.out.println("not a file");
			}
			if(file.renameTo(nFile)){
//				System.out.println("renaming succeeded");
			}else{
//				System.out.println("renaming failed");
			}
		}catch(java.lang.Exception e){
			System.err.println("Exception:" + e);
		}
		
	   	
 		updateLinks(parent, file, nFile, remote);
 		setNodePath(nFile.getPath());
		node.addSortable(this);
 	   	parent.updateTree();	
 	   	parent.saveProject();
	}
	
	protected void updateLinks(Scuttlebutt parent, File file, File nFile, String remote){
	  	Object [] list = filesList.toArray();	
        Tab tab = parent.getEditPane().search(getNodePath());
 		if(tab != null){  
 		}
 	  	
		String temp = new String(new String((getRemoteDirectory().length() > 0)?new String(/*File.separatorChar*/"/" + getRemoteDirectory()) : "") + /*File.separatorChar*/"/" + toString());
 	  	for(Object p : list){
	        Tab t = parent.getEditPane().search((String)p);
	 		String l = new String(new String((remote.length() > 0)? new String(/*File.separatorChar*/"/" + remote) :"") + /*File.separatorChar*/"/" + file.getName());
	 		if(t != null){  
		 		t.replace(temp,l);
	 		}else{
		 		replace((String)p, temp, l);
	 		}
 	  	}
	
		path = nFile.getPath();
		remote_dir = remote;
        
 	   	if(tab != null)
 		   	tab.setFile(nFile.getPath());
	}
	
	protected void replace(String path, String rtx, String nString){
 		String buffer = Open(path);
 		String temp = null;
 		if(buffer != null){
			int pos = buffer.indexOf(rtx);
			if(pos != -1){
				while(pos != -1){
					temp = buffer.replace(rtx, nString);
					pos = buffer.indexOf(rtx, pos + nString.length());
				}
				Save(path, temp);
			}else{
				filesList.remove(path);
			}
 		}else{
	 		filesList.remove(path);
 		}
	}
	
	protected void Save(String path, String data){
		try{
			FileWriter b = new FileWriter(path);
			BufferedWriter w = new BufferedWriter(b);
			w.write(data, 0, data.length());
			w.close();
			b.close();
			
			w = null;
			b = null;

		}catch(IOException io){
			System.err.print(io.getMessage());
		}
		
	}
	
	protected String Open(String f){
		StringBuilder buffer = null;
		try{
		    buffer = new StringBuilder();
			BufferedReader r = new BufferedReader(new FileReader(f));
	 		int val = 0;
	 		while( (val = r.read()) != -1){
		 		buffer.append((char)val);
	 		}
	 		r.close();
		}catch(IOException io){
			System.out.print(io.getMessage());
			return null;
		}
		return buffer.toString();
	}
	
}

